package com.geeguo.ebuilder.client.base.tenant.model;

import com.geeguo.ebuilder.core.common.utils.GsonUtils;
import com.geeguo.ebuilder.core.common.utils.StringHelper;
import com.google.gson.reflect.TypeToken;
import lombok.Getter;
import lombok.Setter;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;

@Getter
@Setter
public class TenantInfo {
    
    private String              id;
    private String              code;
    private String              name;
    private String              domain;
    private String              dataSourceId;
    private String              configJson;
    private boolean             configParsed = false;

    private Map<String, Object> config = null;
    
    public void configParse() {
        if (!configParsed) {
            config = GsonUtils.fromJson(configJson, new TypeToken<>(){});
            configParsed = true;
        }
    }
    
    public Object getConfig(String key) {
        Object result = null;
        if (!configParsed) {
            configParse();
        }
        if (config != null) {
            result = config.get(key);
        }
        return result;
    }

    public String getStringConfig(String key) {
        return getStringConfig(key, null);
    }
    
    public String getStringConfig(String key, String defaultValue) {
        String result = defaultValue;
        Object value = getConfig(key);
        if (value != null) {
            result = String.valueOf(value);
        }
        return result;
    }

    public int getIntegerConfig(String key) {
        return getIntegerConfig(key, 0);
    }

    public int getIntegerConfig(String key, int defaultValue) {
        int resultValue = defaultValue;
        Object value = getConfig(key);
        if (value != null) {
            String valueStr = String.valueOf(value);
            if (StringUtils.isNotEmpty(valueStr) && StringHelper.isDigit(valueStr)) {
                try {
                    resultValue = Integer.valueOf(valueStr);
                } catch (Exception e) {
                    resultValue = defaultValue;
                }
            }
        }
        return resultValue;
    }

    public double getDoubleConfig(String key) {
        return getDoubleConfig(key, 0);
    }

    public double getDoubleConfig(String key, double defaultValue) {
        double resultValue = defaultValue;
        Object value = getConfig(key);
        if (value != null) {
            String valueStr = String.valueOf(value);
            if (StringUtils.isNotEmpty(valueStr) && StringHelper.isDouble(valueStr)) {
                try {
                    resultValue = Double.valueOf(valueStr);
                } catch (Exception e) {
                    resultValue = defaultValue;
                }
            }
        }
        return resultValue;
    }
}